package com.lottery.controller;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.lottery.dao.MemberDao;
import com.lottery.dao.PlayInfoDao;
import com.lottery.dao.UpPlanDao;
import com.lottery.entity.Constants;
import com.lottery.entity.Lottery;
import com.lottery.entity.Member;
import com.lottery.entity.MemberEdit;
import com.lottery.entity.PlayInfo;
import com.lottery.entity.Query;
import com.lottery.entity.Result;
import com.lottery.entity.ResultCode;
import com.lottery.entity.UpPlan;
import com.lottery.util.MailUtil;

@Controller
@RequestMapping("/supervise")
public class MemberManagerController extends BaseController {
	
	@Autowired
	private MemberDao memberDao;
	@Autowired
	private PlayInfoDao playInfoDao;
	@Autowired
	private Mainserver mainserver;
	@Autowired
	private UpPlanDao upPlanDao;
	
	private Logger logger = LoggerFactory.getLogger(MemberManagerController.class);
	@RequestMapping("/addMember")
    public String login(HttpServletRequest req, Model model,Member member) {
		logger.info("-------------------会员信息录入开始-------------------");
		member.setMemberSee(Constants.memberSee);
		logger.info(member.toString());
		int insertMember = memberDao.insertMember(member);
		logger.info("录入记录数为   : "+insertMember);
        return "login";
    }
//	@RequiresRoles(value = "admin")
	@RequestMapping(value = "/listPage", method = RequestMethod.GET, produces = TEXT_HTML)
	public ModelAndView getListManagerPage() {
		Result result = new Result();
		result.setSuccess(true);
		result.resultCode(ResultCode.SUCCESS);
		return respMav("supervise/list", result);
	}
	@RequiresRoles(value = "admin")
	@RequestMapping(value = "/list", method = RequestMethod.GET, produces = TEXT_HTML)
	public ModelAndView list(Member member) {
		List<Member> members = memberDao.findAllMembers();
		Result result = new Result();
		result.data("members", members);
		return respMav("supervise/list", result);
	}
	
	
	@RequestMapping(value = "/editPage")
	public ModelAndView getEditManagerPage(String memberAccount) {
		logger.info("-------------------会员信息修改开始----------查询---------"+memberAccount);
		Member member = memberDao.findMemberByAccount(memberAccount);
		String memberSee = member.getMemberSee();
		List<String> list = new ArrayList<String>();
		if(StringUtils.isNotBlank(memberSee)){
			List<Member> accounts = memberDao.findMemberByAccounts(memberSee.split(","));
			for(Member m : accounts){
				list.add(m.getMemberAccount());
			}
		}
		List<Member> members = memberDao.findMemberByStatus("y");
		MemberEdit memberEdit = new MemberEdit();
		memberEdit.setMemberAccount(memberAccount);
		memberEdit.setMemberNumStatus(member.getMemberNumStatus());
		memberEdit.setMembers(members);	
		memberEdit.setMemberSees(list);
		Result result = new Result();
		result.data("memberEdit", memberEdit);
		return respMav("supervise/edit", result);
	}
	
	@RequestMapping(value = "/edit", method = RequestMethod.POST)
	@ResponseBody
	public Result editManager(@ModelAttribute("memberEdit") MemberEdit memberEdit,Member member) {
		
		logger.info("-----会员信息修改开始------提交---------"+member);
		Result result = new Result();
		int updateFlag = memberDao.updateMemberByAccount(member);
		logger.info("-------------------修改记录数为-------------------"+updateFlag);
		if(updateFlag == 1){
			result.setSuccess(true);
			result.resultCode(ResultCode.SUCCESS);
		}else{
			result.setSuccess(false);
			result.resultCode(ResultCode.Manager_Not_Exist);
		}
		return result;
	}
	
	@RequestMapping(value = "/addPage", method = RequestMethod.GET, produces = TEXT_HTML)
	public ModelAndView getAddManagerPage() {
		Result result = new Result();
		result.setSuccess(true);
		result.resultCode(ResultCode.SUCCESS);
		return respMav("supervise/add", result);
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	@ResponseBody
	public Result addManager(HttpServletRequest req,@ModelAttribute Member member){
		Result result = new Result();
		//判断账号是否存在
		if(memberDao.findMemberByAccount(member.getMemberAccount()) != null){
			result.setSuccess(false);
			result.resultCode(ResultCode.Manager_Has_Exist);
			return result;
		}
		logger.info("-------------------会员信息录入开始-------------------");
		member.setMemberSee(Constants.memberSee);
		logger.info(member.toString());
		String uuid = UUID.randomUUID().toString().replace("-", "");
		member.setFlag(uuid);
		int insertMember = memberDao.insertMember(member);
		logger.info("录入记录数为   : "+insertMember);
		if(insertMember == 1){
			String contextPath = req.getContextPath();
			String url = Constants.local + contextPath + "/activate?id="+member.getMemberAccount()+"&code="+uuid;
			final String content = MailUtil.appendContent(member.getMemberName(), member.getMemberAccount(), member.getMemberPassword(), url);
			final String mail = member.getMemberEmail();
			new Thread(new Runnable(){
				@Override
				public void run() {
					try {
						MailUtil.send(mail, content);
					} catch (Exception e) {
						logger.error(e.getMessage());
					}
				}
			}).start();
			logger.info("----------------path--------------"+contextPath);
			result.setSuccess(true);
			result.resultCode(ResultCode.SUCCESS);
		}else{
			result.setSuccess(false);
			result.resultCode(ResultCode.Manager_Has_Exist);
		}
		return result;
	}
	
	@RequestMapping(value = "playPage")
	public ModelAndView getPlayManagerPage() {
		Result result = new Result();
		result.setSuccess(true);
		result.resultCode(ResultCode.SUCCESS);
		return respMav("supervise/play", result);
	}
	
	@RequestMapping(value = "/play", method = RequestMethod.POST)
	@ResponseBody
	public Result playManager(HttpServletRequest req,@ModelAttribute Member member) {
		Result result = new Result();
		logger.info("member = "+member);
		logger.info("memberPhone =  "+req.getParameter("memberPhone"));
		logger.info("invest =  "+req.getParameter("invest"));
		logger.info("bonus =  "+req.getParameter("bonus"));
		logger.info("playInfo =  "+req.getParameter("playInfo"));
		logger.info("-------------------会员信息录入开始-------------------");
		PlayInfo info = new PlayInfo();
		info.setMemberAccount(req.getParameter("memberAccount"));
		info.setPlay(req.getParameter("playInfo"));
		info.setBonus(Double.parseDouble(req.getParameter("bonus")));
		info.setInvest(Double.parseDouble(req.getParameter("invest")));
		logger.info(info.toString());
		int insertMember = playInfoDao.insertPlayInfo(info);
		logger.info("录入记录数为   : "+insertMember);
		
		if(insertMember == 1){
			result.setSuccess(true);
			result.resultCode(ResultCode.SUCCESS);
		}else{
			result.setSuccess(false);
			result.resultCode(ResultCode.Manager_Has_Exist);
		}
		return result;
	}
	
	@RequestMapping(value = "/pwdPage", method = RequestMethod.GET, produces = TEXT_HTML)
	public ModelAndView getPwdManagerPage() {
		Result result = new Result();
		result.setSuccess(true);
		result.resultCode(ResultCode.SUCCESS);
		return respMav("supervise/pwdEdit", result);
	}
	
	@RequestMapping(value = "/pwd", method = RequestMethod.POST)
	@ResponseBody
	public Result passwordManager(HttpServletRequest req) {
		Result result = new Result();
		logger.info("memberAccount =  "+req.getParameter("memberAccount"));
		logger.info("oldPassword =  "+req.getParameter("oldPassword"));
		logger.info("newPasswrod =  "+req.getParameter("newPasswrod"));
		logger.info("-------------------会员信息录入开始-------------------");
		
		String memberAccount = req.getParameter("memberAccount");
		String oldPassword = req.getParameter("oldPassword");
		String newPasswrod = req.getParameter("newPasswrod");
		int insertMember = memberDao.updatePasswordByAccount(memberAccount, oldPassword, newPasswrod);

		if(insertMember == 1){
			result.setSuccess(true);
			result.resultCode(ResultCode.SUCCESS);
		}else{
			result.setSuccess(false);
			result.resultCode(ResultCode.Update_Old_Password_verify_Error);
		}
		return result;
	}


	@RequestMapping("/record")
	public String record(HttpServletRequest req, HttpServletResponse resp, Model model, HttpSession session, Query query){

		org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
		boolean isAuthenticated = subject.isAuthenticated();

		String principal = (String) subject.getPrincipal();
		boolean admin = subject.hasRole("admin");
		if (!admin) {
			query.setMemberAccount(principal);
		}

		if (StringUtils.isBlank(query.getProvince())) {
			query.setProvince("广东");
		}
		if (StringUtils.isBlank(query.getPlay())) {
			query.setPlay("任2");
		}
		Date d = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if (StringUtils.isBlank(query.getBeginDate())) {
			query.setBeginDate(sdf.format(d));
		}

		List<Lottery> lotteries =  mainserver.getLotteryList(query);
		String hidNO = null;
		if(CollectionUtils.isEmpty(lotteries)){
			hidNO = "01";
			
		}else{
			Set<Integer> ss = new TreeSet<>();
 			for(Lottery ll : lotteries){
 				ss.add(Integer.parseInt(ll.getNo()));
			}
 			int a = 0;
 			for(Integer i : ss){
 				a = i;
 			}
 			hidNO = StringUtils.leftPad(String.valueOf(a+1), 2, '0');
		}
		SimpleDateFormat sdf1 = new SimpleDateFormat("YYYYMMdd");
		String dd = sdf1.format(new Date());
		session.setAttribute("username", principal);
		session.setAttribute("lotteries", lotteries);
		session.setAttribute("hidNO", hidNO);
		session.setAttribute("hidPeriod", dd+hidNO);
		return "/record";

	}

	@ResponseBody
	@RequestMapping(value = {"/find"})
	public Lottery find(String province ,String play,String beginDate,String lastvar,HttpServletRequest request, HttpServletResponse response) {
  System.out.println(province+play+beginDate+lastvar);

		if(StringUtils.isNotBlank(lastvar)){
			org.apache.shiro.subject.Subject subject = SecurityUtils.getSubject();
			String principal = (String) subject.getPrincipal();
			Query query=new Query();
			query.setBeginDate(beginDate);
			query.setProvince(province);
			query.setPlay(play);
			query.setMemberAccount(principal);
			List<Lottery>lotterys=mainserver.getLotteryList(query);
			for(Lottery lottery:lotterys){
				if(Long.valueOf(lastvar)<Long.valueOf(lottery.getPeriods())){
					return lottery;
				}
			}

		}

		return null;
	}

	
	@RequestMapping("/recordInsert")
	public String recordInsert(HttpServletRequest req, String provinceinput ,String playinput, Model model, Lottery lottery){
		logger.info(lottery.toString());
		logger.info(provinceinput);
		logger.info(playinput);
		SimpleDateFormat sdf1 = new SimpleDateFormat("YYYY-MM-dd");
		String txnTime  = sdf1.format(new Date());
		logger.info(txnTime);
		UpPlan up1 = new UpPlan();
		up1.setProvince(provinceinput);
		up1.setPlay(playinput);
		up1.setPeriods(lottery.getPeriods());
		up1.setNumber1(lottery.getNumber1());
		up1.setNumber2(lottery.getNumber1Two());
		up1.setNumber3(lottery.getNumber1Three());
		up1.setMultiple(lottery.getMultiple());
		up1.setScheme("1");
		up1.setTime(txnTime);
		UpPlan up2 = new UpPlan();
		up2.setProvince(provinceinput);
		up2.setPlay(playinput);
		up2.setPeriods(lottery.getPeriods());
		up2.setNumber1(lottery.getNumber2());
		up2.setNumber2(lottery.getNumber2Two());
		up2.setNumber3(lottery.getNumber2Three());
		up2.setMultiple(lottery.getMultipleTwo());
		up2.setScheme("2");
		up2.setTime(txnTime);
		UpPlan up3 = new UpPlan();
		up3.setProvince(provinceinput);
		up3.setPlay(playinput);
		up3.setPeriods(lottery.getPeriods());
		up3.setNumber1(lottery.getNumber3());
		up3.setNumber2(lottery.getNumber3Two());
		up3.setNumber3(lottery.getNumber3Three());
		up3.setMultiple(lottery.getMultipleThree());
		up3.setScheme("3");
		up3.setTime(txnTime);
		int i = upPlanDao.insertUpPlan(up1);
		int j = upPlanDao.insertUpPlan(up2);
		int k = upPlanDao.insertUpPlan(up3);
		logger.info("--------------i--------------"+i);
		logger.info("--------------j--------------"+j);
		logger.info("--------------k--------------"+k);
		return "redirect:record";

	}
}
